package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"net"
	"rpc_demo/rpc_interceptor/proto"
	"time"
)

type Hello1 struct {
}

func (h *Hello1) SayHello(ctx context.Context, req *proto.HelloReq) (*proto.HelloRes, error) {

	return &proto.HelloRes{Data: "2"}, nil
}

const PORT = ":50051"

func main() {

	time.Sleep(time.Second * 10)
	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		panic(err)
	}
	//拦截器
	interceptor := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {

		md, ok := metadata.FromIncomingContext(ctx)
		fmt.Println(md)
		if !ok {
			return resp, status.Errorf(codes.Unauthenticated, "无token")
		}
		var (
			appid  string
			appkey string
		)
		if v, ok := md["appid"]; ok {
			appid = v[0]
		}
		if v, ok := md["appkey"]; ok {
			appkey = v[0]
		}
		fmt.Println(appid, appkey)
		if appid != "234" || appkey != "king" {
			return resp, status.Errorf(codes.Unauthenticated, "无token信息")

		}

		fmt.Println("接收到一条消息")
		return handler(ctx, req)
	}

	opt := grpc.UnaryInterceptor(interceptor)

	s := grpc.NewServer(opt)
	proto.RegisterHelloServer(s, &Hello1{})

	s.Serve(lis)

}
